<template>
    <div>
        <h3>vue-treeselect延迟加载demo</h3>
        <treeselect
            v-model="value"
            :multiple="false"
            :options="options"
            :load-options="loadOptions"
            :auto-load-root-options="false"
            :disable-branch-nodes="true"
            placeholder="请选择..."
            clear-value-text="重置"
            no-children-text="没有子节点啦"
            no-options-text="没有可用选项哦"
            no-results-text="没有匹配的搜索结果"
            loading-text="加载中..."
            retry-text="重试？"
            retry-title="点击重试"
        />
        <h4>选择的结果为：{{ value }}</h4>
    </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
// https://vue-treeselect.js.org/
// https://www.vue-treeselect.cn/
import { Treeselect, LOAD_ROOT_OPTIONS, LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { delaySomeTime } from '@/utils'
@Component({
    components: {
        Treeselect,
    },
})
export default class TreeSelectDelayedLoading extends Vue {
    // 如果不需要回显，应设置为null或undefined（最好用null），否则会显示`unknown`
    value = null
    // 延迟加载根级别选项，所以这里应默认为null
    options: any[] | null = null

    // https://www.vue-treeselect.cn/#delayed-loading
    async loadOptions({ action, parentNode }: any) {
        if (action === LOAD_ROOT_OPTIONS) {
            await delaySomeTime(300)
            this.options = ['a', 'b', 'c', 'd', 'e'].map((id) => ({
                id,
                label: `test-${id}`,
                children: null,
            }))
        } else if (action === LOAD_CHILDREN_OPTIONS) {
            await delaySomeTime(300)
            parentNode.children = ['呵呵', '哈哈', '啦啦', '略略', '哦哦'].map((id, index) => ({
                id: parentNode.id + '_' + index,
                label: `${parentNode.label}-${id}`,
                // 设为undefined或直接不给children表示其为叶子节点
                // 设为null表示可能还存在子节点，展开时继续调用loadOptions
                children: index % 2 === 0 ? null : undefined,
            }))
        }
    }
}
</script>
